package org.example.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.config.R;
import org.example.domain.Dict;
import org.example.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("dict")
public class DictController {
    @Autowired
    DictService dictService;

    @RequestMapping("dictList")
    public R dictList(@RequestBody Dict dict, Page page){
        PageHelper.startPage((int) page.getCurrent(), (int) page.getSize());
        List<Dict> list = dictService.dictList(dict);
        PageInfo<Dict> dictPageInfo = new PageInfo<>(list);
        return R.successed(dictPageInfo);
    }

    @RequestMapping("dictAdd")
    public R dictAdd(@RequestBody Dict dict){
        return dictService.dictAdd(dict);
    }

    @RequestMapping("delById")
    public R delById(Integer id){
        return dictService.delById(id);
    }

    @RequestMapping("delAll")
    public R delAll(Integer[] ids){
        for (Integer id : ids) {
            dictService.delById(id);
        }
        return R.successed(null);
    }
    @RequestMapping("updateById")
    public R updateById(@RequestBody Dict dict){
        return dictService.updateById(dict);
    }
    @Autowired
    HttpServletResponse response;
    @RequestMapping("excel")
    public R excel() throws IOException {
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);

//自定义标题别名
        writer.addHeaderAlias("id", "id");
        writer.addHeaderAlias("title", "title");
        writer.addHeaderAlias("type", "type");
        writer.addHeaderAlias("status", "status");
        writer.addHeaderAlias("context", "context");
        writer.addHeaderAlias("create_time", "create_time");
        writer.addHeaderAlias("flag", "flag");

        List<Dict> list = dictService.list();

        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=test.xlsx");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
        return R.successed(null);
    }

}
